package com.eb.aspect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eb.annotation.AutoAnnouncement;
import com.eb.context.BaseContext;
import com.eb.domain.Announcement;
import com.eb.domain.Innovation;
import com.eb.domain.Look;
import com.eb.domain.User;
import com.eb.dto.CommentDto;
import com.eb.enumeration.OperationType;
import com.eb.mapper.IAnnouncementMapper;
import com.eb.mapper.IInnovationMapper;
import com.eb.mapper.ILookMapper;
import com.eb.mapper.IUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义切面，实现自动通知
 */
@Aspect
@Slf4j
@Component
public class AutoAnnounceAspect {
    /**
     * 切入点，对哪些类的哪些方法进行拦截
     */
    @Pointcut("execution(* com.eb.service.impl.*.*(..)) && @annotation(com.eb.annotation.AutoAnnouncement)")
    public void AutoAnnoPointCut(){}


    @Autowired
    private IAnnouncementMapper announcementMapper;
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private IInnovationMapper innovationMapper;
    @Autowired
    private ILookMapper lookMapper;

    /**
     * 后置返回通知，通知中进行自动向用户发送通知
     */
    @AfterReturning(pointcut = "AutoAnnoPointCut()",returning = "res")
    public void autoFill(JoinPoint joinPoint,Object res){
        log.info("开始进行自动发送通知...");
        //1.获取业务操作类型
        //1-1 方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //1-2获取注解对象,操作类型
        AutoAnnouncement announcement = signature.getMethod().getAnnotation(AutoAnnouncement.class);
        OperationType type = announcement.value();

        //2.获取方法参数--实体对象
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0)
        {
            //没有参数，直接返回
            return;
        }
        Object entity = args[0];

        //3.根据对象数据发送通知
        if (type != OperationType.COMMENT)
        {
            if (type == OperationType.PRESERVE)
            {
                if (!(Boolean) res )
                    return;
            }
            Integer innovationId = (Integer) entity;
            log.info("帖子id:{}",(Integer)entity);
            //如果是浏览，且已经浏览过，那么方法不必继续执行
            if (type == OperationType.LOOK)
            {
                QueryWrapper<Look> wrapper = new QueryWrapper<>();
                wrapper.eq("innovation_id",innovationId)
                        .eq("user_id",BaseContext.getCurrentId());
                Look look = lookMapper.selectOne(wrapper);
                if (look != null)
                    return;
            }
            //查询操作人的用户名
            User user = userMapper.selectById(BaseContext.getCurrentId());
            String preserveName = user.getNickname();
            //查询帖子标题
            QueryWrapper<Innovation> wrapper = new QueryWrapper<>();
            wrapper.select("title","user_id");
            wrapper.eq("id",innovationId);
            Innovation innovation = innovationMapper.selectOne(wrapper);
            String title = innovation.getTitle();
            //截取前15个字
            if (title.length() >15)
                title = title.substring(0,15)+"...";
            //拼接信息
            String message = preserveName+type.getName()+"了你的帖子"+"，该帖子标题为："+"'"+title+"'";
            log.info("信息:{}",message);
            //将消息写入数据库
            Announcement announcement1 = new Announcement();
            announcement1.setContent(message);
            announcement1.setCreateTime(LocalDateTime.now());
            announcement1.setUserId(innovation.getUserId());
            announcementMapper.insert(announcement1);
        }else
        {
            log.info("帖子id:{}",(CommentDto)entity);
            CommentDto commentDto = (CommentDto) entity;
            //查询评论人的用户名
            User user = userMapper.selectById(BaseContext.getCurrentId());
            String userNickname = user.getNickname();
            //查询帖子标题
            QueryWrapper<Innovation> wrapper = new QueryWrapper<>();
            wrapper.select("title","user_id");
            wrapper.eq("id",commentDto.getInnovationId());
            Innovation innovation = innovationMapper.selectOne(wrapper);
            String title = innovation.getTitle();
            //截取前15个字
            if (title.length() >15)
                title = title.substring(0,15)+"...";
            //拼接信息
            String message = userNickname+type.getName()+"了你的帖子"+"，该帖子标题为："+"'"+title+"'";
            String content =
            message+="该评论的内容为：" +"'"+commentDto.getContent()+"'";
            log.info("信息:{}",message);
            //将消息写入数据库
            Announcement announcement1 = new Announcement();
            announcement1.setContent(message);
            announcement1.setCreateTime(LocalDateTime.now());
            announcement1.setUserId(innovation.getUserId());
            announcementMapper.insert(announcement1);
        }



    }

}
